package com.hue.gulimailssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @author 姚凤桥
 * @Date 2021/11/29 10:58
 * @Description:
 */
@Controller
public class HelloController {
    @Value("${login.url}")
    private String loginUrl;

    /**
     * hello请求不需要登录
     *
     * @return
     */
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * users请求必须要登录
     *
     * @return
     */
    @GetMapping("users")
    public String users(HttpSession session, Model model, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            //查询用户的信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> res = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String userInfo = res.getBody();
            session.setAttribute("userInfo", userInfo);

            session.setAttribute("user", token);
        }

        Object user = session.getAttribute("user");
        if (user != null) {
            List<String> users = Arrays.asList("张三", "李四");
            model.addAttribute("users", users);
            return "users";
        }

        //没有登录，跳转到登录服务器，并且带上当前资源的地址，用于在用户登录成功后跳转回来
        return "redirect:" + loginUrl + "?redirectUrl=http://client1.com:8081/users";
    }

}
